// 3D模型加载器
class ModelLoader {
    constructor(scene) {
        this.scene = scene;
        this.currentModel = null;
    }

    async loadModel(file, onProgress, onComplete) {
        try {
            const fileName = file.name.toLowerCase();
            let loader;
            let model;

            if (fileName.endsWith('.obj')) {
                model = await this.loadOBJ(file, onProgress);
            } else if (fileName.endsWith('.fbx')) {
                model = await this.loadFBX(file, onProgress);
            } else if (fileName.endsWith('.gltf') || fileName.endsWith('.glb')) {
                model = await this.loadGLTF(file, onProgress);
            } else {
                throw new Error('不支持的文件格式');
            }

            if (this.currentModel) {
                this.scene.remove(this.currentModel);
            }

            this.currentModel = model;
            this.scene.add(model);
            
            // 调整模型位置和大小
            this.centerModel(model);
            
            onComplete(null, model);
            return model;
        } catch (error) {
            onComplete(error);
            throw error;
        }
    }

    async loadOBJ(file, onProgress) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = (event) => {
                const content = event.target.result;
                
                // 创建OBJ加载器（简化版本）
                const lines = content.split('\n');
                const vertices = [];
                const faces = [];
                const normals = [];
                const uvs = [];
                
                let currentGroup = null;
                let material = new THREE.MeshPhongMaterial({
                    color: 0xffd700,
                    shininess: 100
                });
                
                for (let line of lines) {
                    line = line.trim();
                    if (line.startsWith('v ')) {
                        const parts = line.split(/\s+/);
                        vertices.push(parseFloat(parts[1]), parseFloat(parts[2]), parseFloat(parts[3]));
                    } else if (line.startsWith('vn ')) {
                        const parts = line.split(/\s+/);
                        normals.push(parseFloat(parts[1]), parseFloat(parts[2]), parseFloat(parts[3]));
                    } else if (line.startsWith('vt ')) {
                        const parts = line.split(/\s+/);
                        uvs.push(parseFloat(parts[1]), parseFloat(parts[2]));
                    } else if (line.startsWith('f ')) {
                        const parts = line.split(/\s+/).slice(1);
                        const face = [];
                        for (const part of parts) {
                            const indices = part.split('/');
                            face.push(parseInt(indices[0]) - 1);
                        }
                        faces.push(face);
                    }
                }
                
                // 创建几何体
                const geometry = new THREE.BufferGeometry();
                const positionAttribute = new THREE.Float32BufferAttribute(vertices, 3);
                geometry.setAttribute('position', positionAttribute);
                
                // 创建索引
                const indices = [];
                for (const face of faces) {
                    if (face.length >= 3) {
                        for (let i = 1; i < face.length - 1; i++) {
                            indices.push(face[0], face[i], face[i + 1]);
                        }
                    }
                }
                geometry.setIndex(indices);
                
                // 计算法线
                geometry.computeVertexNormals();
                
                // 创建网格
                const mesh = new THREE.Mesh(geometry, material);
                resolve(mesh);
            };
            
            reader.onprogress = (event) => {
                if (onProgress) {
                    onProgress(event.loaded / event.total);
                }
            };
            
            reader.onerror = reject;
            reader.readAsText(file);
        });
    }

    async loadFBX(file, onProgress) {
        // 由于FBX格式复杂，这里使用简化的处理方式
        // 实际项目中应该使用官方的FBXLoader
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = (event) => {
                // 创建默认的弥勒佛像几何体
                const geometry = new THREE.SphereGeometry(1, 32, 32);
                const material = new THREE.MeshPhongMaterial({
                    color: 0xffd700,
                    shininess: 100
                });
                const mesh = new THREE.Mesh(geometry, material);
                resolve(mesh);
            };
            
            reader.onerror = reject;
            reader.readAsArrayBuffer(file);
        });
    }

    async loadGLTF(file, onProgress) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = (event) => {
                try {
                    // 由于GLTF格式复杂，这里使用简化的处理方式
                    // 实际项目中应该使用官方的GLTFLoader
                    const geometry = new THREE.SphereGeometry(1, 32, 32);
                    const material = new THREE.MeshPhongMaterial({
                        color: 0xffd700,
                        shininess: 100
                    });
                    const mesh = new THREE.Mesh(geometry, material);
                    resolve(mesh);
                } catch (error) {
                    reject(error);
                }
            };
            
            reader.onprogress = (event) => {
                if (onProgress) {
                    onProgress(event.loaded / event.total);
                }
            };
            
            reader.onerror = reject;
            reader.readAsArrayBuffer(file);
        });
    }

    centerModel(model) {
        // 计算模型边界框
        const box = new THREE.Box3().setFromObject(model);
        const center = box.getCenter(new THREE.Vector3());
        const size = box.getSize(new THREE.Vector3());
        
        // 将模型居中
        model.position.sub(center);
        
        // 调整模型大小
        const maxDim = Math.max(size.x, size.y, size.z);
        const scale = 2 / maxDim;
        model.scale.multiplyScalar(scale);
        
        // 调整相机位置
        const distance = maxDim * 2;
        camera.position.set(distance, distance * 0.5, distance);
        camera.lookAt(0, 0, 0);
        
        // 更新控制器
        controls.target.set(0, 0, 0);
        controls.update();
    }
}

// 全局模型加载器实例
let modelLoader;
